package com.jml.config;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class RedissonConfig {

    @Autowired
    private RedisConfigProperties redisConfigProperties;

    /**
     * 优先级：cluster->sentinel->single
     * @return
     */
    @Bean
    public RedissonClient getRedisson() {
        Config config = new Config();
        //cluster集群
        if(redisConfigProperties.getCluster()!=null && !(CollectionUtils.isEmpty(redisConfigProperties.getCluster().getNodes()))){
            List<String> clusterNodes = new ArrayList<>();
            for (int i = 0; i < redisConfigProperties.getCluster().getNodes().size(); i++) {
                clusterNodes.add("redis://" + redisConfigProperties.getCluster().getNodes().get(i));
            }
            config.useClusterServers()
                    .addNodeAddress(clusterNodes.toArray(new String[clusterNodes.size()]))
                    .setPassword(redisConfigProperties.getPassword());//设置密码
        // 主从
        }else if(redisConfigProperties.getSentinel()!=null && StringUtils.isNotBlank(redisConfigProperties.getSentinel().getMaster())){
            List<String> sentinelNodes = new ArrayList<>();
            for (int i = 0; i < redisConfigProperties.getSentinel().getNodes().size(); i++) {
                sentinelNodes.add("redis://" + redisConfigProperties.getSentinel().getNodes().get(i));
            }
            config.useMasterSlaveServers().setMasterAddress("redis://" + redisConfigProperties.getSentinel().getMaster())
                    .setPassword(redisConfigProperties.getPassword())
                    .addSlaveAddress(sentinelNodes.toArray(new String[sentinelNodes.size()]));
        //单点
        }else if(StringUtils.isNotBlank(redisConfigProperties.getHost())){
            config.useSingleServer().setAddress("redis://" + redisConfigProperties.getHost() + ":" + redisConfigProperties.getPort())
                    /*.setPassword(redisConfigProperties.getPassword())*/;
        }else{
            throw new RuntimeException("redisson锁配置有误");
        }
        return Redisson.create(config);
    }
}